import React, {useState} from "react";
import {Card, Input, Button, Spin, message} from "antd";
import {UserOutlined, LockOutlined} from "@ant-design/icons";
import "../static/css/login.css"
import servicePath from "../config/apiUrl";
import axios from "axios";


function Login(props) {

    const [usernName, setUserName] = useState("");
    const [password, setPassword] = useState("");
    const [isLoading, setInLoading] = useState(false);

    const checkLogin = () => {
        setInLoading(true);
        if (!usernName) {
            message.error("用户名不可以为空")
            setTimeout(() => {
                setInLoading(false)
            }, 500)
            return
        } else if (!password) {
            message.error("密码不可以为空");
            setTimeout(() => {
                setInLoading(false)
            }, 500)
            return
        }
        let dataProps = new FormData();
        dataProps.append("username", usernName)
        dataProps.append("password", password)

        axios({
            method: 'post',
            url: servicePath.checkLogin,
            data: dataProps,
        }).then(
            res => {
                setInLoading(false)
                if (res.status === 200) {
                    localStorage.setItem('openId', res.data.openId);
                    localStorage.setItem("user", usernName);
                    props.history.push('/index');
                } else {
                    message.error('用户名密码错误');
                }
            }
        ).catch(function (err) {
            message.error('用户名密码错误');
            localStorage.removeItem('openId');
            localStorage.removeItem('user')
        })




        setTimeout(() => {
            setInLoading(false)
        }, 500)
    }


    return (
        <div className="login-div">
            <Spin tip="Loading...." spinning={isLoading}>
                <Card title="谷之也博客 Admin" bordered={true} style={{width: 400}}>
                    <Input
                        id="userName"
                        size="large"
                        placeholder="请输入用户名"
                        prefix={<UserOutlined/>}
                        onChange={(e) => {
                            setUserName(e.target.value)
                        }}/>
                    <br/><br/>
                    <Input
                        id="password"
                        size={"large"}
                        placeholder={"请输入密码"}
                        prefix={<LockOutlined/>}
                        onChange={(e) => {
                            setPassword(e.target.value)
                        }}/>
                    <br/><br/>

                    <Button type="primary" size="large" block onClick={checkLogin}>Login in</Button>
                </Card>
            </Spin>
        </div>
    )
}


export default Login